package com.bdqn.controller;

import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysRoleService;
import com.bdqn.service.SysUserService;
import com.bdqn.util.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class SysUserController {

    @Resource
    private SysUserService userService;
    @Resource
    private SysRoleService roleService;

    /**
     * 分页查询功能
     * @param model
     * @param queryRealName
     * @param queryRoleId
     * @param pageIndex
     * @return
     */
    @GetMapping("/user/list")
    public String toUserList(Model model , @RequestParam(value = "queryRealName" , required = false) String queryRealName , @RequestParam(value = "queryRoleId" , required = false) Long queryRoleId , @RequestParam(value = "pageIndex" , required = false , defaultValue = "1") Long pageIndex){

        //给角色下拉框添加内容
        List<SysRole> roleList = roleService.list();

        //查询符合条件的用户
        Long count = userService.count(queryRealName, queryRoleId);

        //更具条件查询分页数据
        Page<SysUser> page = new Page<>();
        page.setPageSize(5L);
        page.setTotalCount(count);
        page.setCurrentPageNo(pageIndex);
        List<SysUser> list = userService.page(queryRealName , queryRoleId , page);
        page.setData(list);

        //设置作用域
        model.addAttribute("queryRealName" , queryRealName);//用户填写的内容
        model.addAttribute("queryRoleId" , queryRoleId);//用户选择的下拉项
        model.addAttribute("roleList" , roleList);//下拉列表
        model.addAttribute("page" , page);//查到的分页数据

        return "sysUser/list";
    }


    /**
     * 添加功能
     */
    @GetMapping("/user/add")
    public String toAdd() {
        return "sysUser/add";
    }

    @PostMapping("/user/add")
    public String doAdd(SysUser user) {

        int a = userService.add(user);

        return "sysUser/add";
    }

    @GetMapping("user/del/{userid}")
    public String del(@PathVariable Integer id){

        int result = userService.del(id);

        return result > 0 ? "true" : "false";
    }
}